//
//  SearchViewController.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/9/6.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

#import "SearchViewController.h"
#import "NSDictionary+Safety.h"
#import "ListViewController.h"
#import "SearchHotCollectionViewCell.h"
#import "SearchHotCollectionReusableView.h"
#import "SearchHistoryTableViewCell.h"
#import "NetManager.h"
#import "User.h"
@interface SearchViewController ()<UITextFieldDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
@end

@implementation SearchViewController

#pragma mark - lifeCycle
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 50.0;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.searchTextField.text = self.searchKeywords;
    [self.searchTextField becomeFirstResponder];
    
    self.navigationController.navigationBar.hidden = YES;
    
    [self fetchSearchData];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    BOOL result = [textField resignFirstResponder];
    ListViewController *listVC = [ListViewController listVCFromStroyBoard];
    if (textField.text.length == 0) {
        listVC.searchFoodTitle = textField.placeholder;
    }else {
        listVC.searchFoodTitle = textField.text;
    }
    listVC.title = listVC.searchFoodTitle;
    [self.navigationController pushViewController:listVC animated:YES];
    return result;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.searchData safeObjectForKey:@"history"] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"historyCell" forIndexPath:indexPath];
    cell.label.text = [[self.searchData safeObjectForKey:@"history"][indexPath.row] safeObjectForKey:@"name"];
    __weak typeof(self) ws = self;
    cell.clearAction = ^{
        [ws clearHistoryWithID:[[ws.searchData safeObjectForKey:@"history"][indexPath.row] safeObjectForKey:@"id"]];
    };
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ListViewController *listVC = [ListViewController listVCFromStroyBoard];
    SearchHistoryTableViewCell *cell = (SearchHistoryTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    listVC.searchFoodTitle = cell.label.text;
    listVC.title = cell.label.text;
    [self.navigationController pushViewController:listVC animated:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
    label.text = @"  最近搜索";
    label.font = [UIFont fontWithName:@"AppleSDGothicNeo-Regular" size:17.0];
    
    UIButton *clearAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    clearAllBtn.frame = CGRectMake(self.view.bounds.size.width - 60, 0, 40, 40);
    [clearAllBtn setTitle:nil forState:UIControlStateNormal];
    [clearAllBtn setImage:[UIImage imageNamed:@"clearAll"] forState:UIControlStateNormal];
    [clearAllBtn addTarget:self action:@selector(clearAllHistory) forControlEvents:UIControlEventTouchUpInside];
    UIView *header = [[UIView alloc] init];
    if ([[self.searchData safeObjectForKey:@"history"] count] != 0) {
        [header addSubview:label];
        [header addSubview:clearAllBtn];
    }
    return header;
}
#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [[self.searchData safeObjectForKey:@"hot"] count];
}
- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    SearchHotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hotCell" forIndexPath:indexPath];
    cell.label.text = [[self.searchData safeObjectForKey:@"hot"][indexPath.row] safeObjectForKey:@"name"];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ListViewController *listVC = [ListViewController listVCFromStroyBoard];
    SearchHotCollectionViewCell *cell = (SearchHotCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    listVC.searchFoodTitle = cell.label.text;
    listVC.title = cell.label.text;
    [self.navigationController pushViewController:listVC animated:YES];
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    SearchHotCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hotResuableView" forIndexPath:indexPath];
    if ([[self.searchData safeObjectForKey:@"hot"] count] != 0) {
        header.label.text = @"热门搜索";
    }
    return header;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *text = [[self.searchData safeObjectForKey:@"hot"][indexPath.row] safeObjectForKey:@"name"];
    UIFont *font = [UIFont fontWithName:@"AppleSDGothicNeo-Regular" size:15+3.0];
    CGSize size = CGSizeMake(MAXFLOAT, 30.0f);
    CGSize buttonSize = [text boundingRectWithSize:size
                                           options:NSStringDrawingTruncatesLastVisibleLine  | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                        attributes:@{NSFontAttributeName:font}
                                           context:nil].size;
    return CGSizeMake(buttonSize.width + 22, buttonSize.height + 2);
}
#pragma mark - event response
- (IBAction)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)clearAllHistory {
    [self clearHistoryWithID:nil];
}
- (void)clearHistoryWithID:(NSString *)historyID {
    NSDictionary *params;
    if (historyID) {
        params = @{@"uid":[User userID], @"id":historyID};
    }else {
        params = @{@"uid":[User userID]};
    }
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/del_search" params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([[responseObject safeObjectForKey:@"code"] isEqual:@1]) {
            [self fetchSearchData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - public
+ (instancetype)searchVCFromStoryBoard {
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"SearchVC"];
}
#pragma mark - private
- (void)fetchSearchData {
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/search" params:@{@"uid":[User userID]} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.searchData = [responseObject safeObjectForKey:@"show_data"];
        self.searchTextField.placeholder = [[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"default"];
        [self.collectionView reloadData];
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - setter
- (void)setSearchKeywords:(NSString *)searchKeywords {
    _searchKeywords = searchKeywords;
}

@end
